<?php

// @formatter:off
/**
 * @file CTNoPrefix.php
 * @author Alejandro Dario Simi
 * @date $Date: 2014-05-04 01:33:52 +0000 (Sun, 04 May 2014) $
 *
 * $Id: CTNoPrefix.php 111 2014-05-04 01:33:52Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/trunk/extensions/NoPrefix/includes/CTNoPrefix.php $
 */
class CTNoPrefix extends WCCronTool {
	//
	// Protected variables.
	protected $_config = false;
	protected $_prefixes = array();
	//
	// Magic methods.
	/**
	 * Class constructor.
	 */
	public function __construct() {
		parent::__construct();
		$this->loadConfig();
	}
	//
	// Public methods.
	public function run($spacer = "") {
		global $wcOptions;

		$stmtCMC = null;
		$stmtId = __CLASS__."::".__FUNCTION__."[cmc]";
		if($this->_db->has($stmtId)) {
			$stmtCMC = $this->_db->get($stmtId);
		} else {
			$query = "select  mem_comic,\n";
			$query .= "        count(*) as mem_count\n";
			$query .= "from    {$this->_dbprefix}tag_comics\n";
			$query .= "where   mem_comic in (\n";
			$query .= "                select  mem_comic\n";
			$query .= "                from    {$this->_dbprefix}tag_comics\n";
			$query .= "                where   mem_tag   = :tag\n";
			$query .= "                 and    mem_group = :group)\n";
			$query .= " and    mem_comic in (\n";
			$query .= "                select  mem_comic\n";
			$query .= "                from    {$this->_dbprefix}tag_comics\n";
			$query .= "                                inner join {$this->_dbprefix}tags\n";
			$query .= "                                        on (mem_group = tag_group and mem_tag = tag_id)\n";
			$query .= "                where   mem_tag   <> :tag\n";
			$query .= "                 and    mem_group =  :group\n";
			$query .= "                 and    tag_name like :prefix)\n";
			$query .= " and    mem_group = :group\n";
			$query .= "group by mem_comic\n";
			$stmtCMC = $this->_db->prepare($stmtId, $query);
		}
		$stmtIMG = null;
		$stmtId = __CLASS__."::".__FUNCTION__."[img]";
		if($this->_db->has($stmtId)) {
			$stmtIMG = $this->_db->get($stmtId);
		} else {
			$query = "select  mem_image,\n";
			$query .= "        count(*) as mem_count\n";
			$query .= "from    {$this->_dbprefix}tag_images\n";
			$query .= "where   mem_image in (\n";
			$query .= "                select  mem_image\n";
			$query .= "                from    {$this->_dbprefix}tag_images\n";
			$query .= "                where   mem_tag   = :tag\n";
			$query .= "                 and    mem_group = :group)\n";
			$query .= " and    mem_image in (\n";
			$query .= "                select  mem_image\n";
			$query .= "                from    {$this->_dbprefix}tag_images\n";
			$query .= "                                inner join {$this->_dbprefix}tags\n";
			$query .= "                                        on (mem_group = tag_group and mem_tag = tag_id)\n";
			$query .= "                where   mem_tag   <> :tag\n";
			$query .= "                 and    mem_group =  :group\n";
			$query .= "                 and    tag_name like :prefix)\n";
			$query .= " and    mem_group = :group\n";
			$query .= "group by mem_image\n";
			$stmtIMG = $this->_db->prepare($stmtId, $query);
		}

		$groupId = $wcOptions->activated("Group") ? $wcOptions->value("Group") : false;

		foreach(WCGroupsHolder::I()->items() as $group) {
			//
			// Ignoring not matching groups when there's a specified
			// one.
			if($groupId && $group->id != $groupId) {
				continue;
			}
			if(is_readable($group->root)) {
				echo "{$spacer}Checking group '{$group}':\n";

				foreach($this->_prefixes as $prefix) {
					echo "{$spacer}\tChecking prefix '{$prefix["prefix"]}*':\n";
					$tag = WCTagsHolder::I()->itemByNameInGroup($prefix["tag"], $group);
					$tag = array_shift($tag);
					if(!$tag) {
						$tag = WCTagsHolder::I()->createInGroup($prefix["tag"], $group);
					}

					$params = array(
						":group" => $group->id,
						":tag" => $tag->id,
						":prefix" => "{$prefix["prefix"]}%"
					);
					//
					// Removing tagged comics.
					if($stmtCMC->execute($params) && $stmtCMC->rowCount() > 0) {
						$holder = WCComicsHolder::I();
						foreach($stmtCMC->fetchAll() as $row) {
							if($row["mem_count"] > 0) {
								$comic = $holder->item($row["mem_comic"]);
								if($comic && $comic->ok() && $comic->group == $group->id) {
									echo "{$spacer}\t\tRemoving comic '{$comic}' from tag '{$tag}': ";
									if($tag->removeComic($comic)) {
										echo WCColorText::ShellGreen("Done\n");
									} else {
										echo WCColorText::ShellRed("Failed\n");
									}
								}
							}
						}
					}
					//
					// Removing tagged images.
					if($stmtIMG->execute($params) && $stmtIMG->rowCount() > 0) {
						$holder = WCImagesHolder::I();
						foreach($stmtIMG->fetchAll() as $row) {
							if($row["mem_count"] > 0) {
								$image = $holder->item($row["mem_image"]);
								if($image && $image->ok() && $image->group == $group->id) {
									echo "{$spacer}\t\tRemoving image '{$image}' from tag '{$tag}': ";
									if($tag->removeImage($image)) {
										echo WCColorText::ShellGreen("Done\n");
									} else {
										echo WCColorText::ShellRed("Failed\n");
									}
								}
							}
						}
					}
				}
			}
		}
	}
	public function showHelp($spacer = "") {
		//echo "{$spacer}This tool adds tag '{self::$TagNoName}' to any comics without
		// tags.\n\n";
		echo "{$spacer}Options:\n";
		echo "{$spacer}\t-g group-id, --group group-id\n";
		echo "{$spacer}\t\tIt only for a specific group.\n\n";
	}
	//
	// Protected methods.
	protected function loadConfig() {
		$this->_config = json_decode(file_get_contents(WC_E_NOPREFIX_ROOTDIR."/config.json"));
		if(isset($this->_config->prefixes)) {
			foreach($this->_config->prefixes as $prefix) {
				$this->_prefixes[] = array(
					"prefix" => $prefix->prefix,
					"tag" => $prefix->tag
				);
			}
		}
	}
	protected function loadOptions() {
		if(!$this->_optionsLoaded) {
			global $wcOptions;

			if($wcOptions->addValueOption("Group")) {
				$wcOptions->addOptionTrigger("Group", "g");
				$wcOptions->addOptionTrigger("Group", "group");
			}

			$wcOptions->check();

			$this->_optionsLoaded = true;
		}
	}
}
